<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/* * *****************************************************************************
 * Title           Photos
 *
 * @package        LMJ-elephanti
 * Location        application/frontend/controllers/media
 *
 * @author         Sugunan - <<sugunan.kumaraguru[at]cyberlmj[dot]com>>
 * @copyright      Cyber L-M-J
 *
 * created on      26-04-2012, 01:16PM by Sugunan
 * updated on      26-04-2012, 01:56PM by Sugunan
 *
 * Description:    System photo reference goes through this controller.
 * *****************************************************************************
 */

class photos extends CI_Controller 
{

    public function __construct() {
    	parent::__construct();
        $this->media_url = $this->config->item('media_web_path');
    }
    
    public function index() {
    	show_404();
        die;
    }
    
    /**
	 * -------------------------------------------------------
	 * METHOD: cropped
	 * -------------------------------------------------------
	 *
	 * This is crope the image to fill the box remain need to be hidden by wrapper div overflow.
	 * Function need to be called through following url
	 * http://elephanti.com/media/photos/cropped/400/300/merchant/profile/albums/test/mac.gif
	 * refer base url through config key : [cdn_url]
	 * 
	 * So explanation will be like this 
	 * http://elephanti.com/media/photos/cropped/width/height/dir1/dir2/image.gif
	 * 
	 * Here width and height is very important in same order but folder structure and file we can go in any level
	 * 
	 * @param (int)    width     |   with of the wraper content
	 * @param (int)    height    |   height of the wraper content
	 * @param (string) url    	 |   url of the image
	 *
	 */
    public function cropped()
    {
    	$args = func_get_args();		// assigning all parameters to variable as an array
    	
    	$width = $args[0];
		$height = $args[1];
		$filename = "";
    	
    	/**
    	 * validating for minimum 3 parameters
    	 */
    	if(count($args)<3 || !is_numeric($width) || !is_numeric($height))
    	{
    		show_404();
        	die;
    	}   	
		
		$path_array = array_slice($args,2);		// extract the url parameter in sub array		
		
		/**
		 * building url within cdn
		 */
		foreach($path_array as $path_val)
		{
			if($filename != "")
			{
				$filename .= "/";
			}
			
			$filename .= $path_val;
		}

		$filename = $this->media_url . $filename;
		
		$image_info = getimagesize($filename);
		
		$image_type = $image_info[2];
		
		if ($image_type == IMAGETYPE_JPEG) 
		{
			$image = imagecreatefromjpeg($filename);
			
            $dim = $this->fill($width,$height,imagesx($image),imagesy($image));
			
			$new_image = imagecreatetruecolor($dim['w'], $dim['h']);
			imagecopyresampled($new_image, $image, 0, 0, 0, 0, $dim['w'], $dim['h'], imagesx($image), imagesy($image));
			$image = $new_image;
			
			header("content-type:image/jpeg");
			imagejpeg($image);
			
		}
		elseif ($image_type == IMAGETYPE_GIF) 
		{
			$image = imagecreatefromgif($filename);

            $dim = $this->fill($width,$height,imagesx($image),imagesy($image));
			
			$new_image = imagecreatetruecolor($dim['w'], $dim['h']);
			imagecopyresampled($new_image, $image, 0, 0, 0, 0, $dim['w'], $dim['h'], imagesx($image), imagesy($image));
			$image = $new_image;
			
			header("content-type:image/gif");
			imagegif($image);
		}
		elseif ($image_type == IMAGETYPE_PNG) 
		{
			$image = imagecreatefrompng($filename);
			
            $dim = $this->fill($width,$height,imagesx($image),imagesy($image));
			
			$new_image = imagecreatetruecolor($dim['w'], $dim['h']);
			imagecopyresampled($new_image, $image, 0, 0, 0, 0, $dim['w'], $dim['h'], imagesx($image), imagesy($image));
			$image = $new_image;
			
			header("content-type:image/png");
			imagepng($image);
		}
    }
    
    /**
	 * -------------------------------------------------------
	 * METHOD: proportionally_cropped
	 * -------------------------------------------------------
	 *
	 * This is crope the image propotionally within defined with and height.
	 * Function need to be called through following url
	 * http://elephanti.com/media/photos/proportionally_cropped/400/300/merchant/profile/albums/test/mac.gif
	 * refer base url through config key : [cdn_url]
	 * 
	 * So explanation will be like this 
	 * http://elephanti.com/media/photos/proportionally_cropped/width/height/dir1/dir2/image.gif
	 * 
	 * Here width and height is very important in same order but folder structure and file we can go in any level
	 * 
	 * @param (int)    width     |   with of the wraper content
	 * @param (int)    height    |   height of the wraper content
	 * @param (string) url    	 |   url of the image
	 *
	 */
    public function proportionally_cropped()
    {
    	$args = func_get_args();		// assigning all parameters to variable as an array
    	
    	$width = $args[0];
		$height = $args[1];
		$filename = "";
    	
    	/**
    	 * validating for minimum 3 parameters
    	 */
    	if(count($args)<3 || !is_numeric($width) || !is_numeric($height))
    	{
    		show_404();
        	die;
    	}   	
		
		$path_array = array_slice($args,2);		// extract the url parameter in sub array		
		
		/**
		 * building url within cdn
		 */
		foreach($path_array as $path_val)
		{
			if($filename != "")
			{
				$filename .= "/";
			}
			
			$filename .= $path_val;
		}

		$filename = $this->media_url . $filename;
		
		$image_info = getimagesize($filename);
		
		$image_type = $image_info[2];
		
		if ($image_type == IMAGETYPE_JPEG) 
		{
			$image = imagecreatefromjpeg($filename);
			
            $dim = $this->resize($width,$height,imagesx($image),imagesy($image));
			
			$new_image = imagecreatetruecolor($dim['w'], $dim['h']);
			imagecopyresampled($new_image, $image, 0, 0, 0, 0, $dim['w'], $dim['h'], imagesx($image), imagesy($image));
			$image = $new_image;
			
			header("content-type:image/jpeg");
			imagejpeg($image);
			
		}
		elseif ($image_type == IMAGETYPE_GIF) 
		{
			$image = imagecreatefromgif($filename);
			
            $dim = $this->resize($width,$height,imagesx($image),imagesy($image));
			
			$new_image = imagecreatetruecolor($dim['w'], $dim['h']);
			imagecopyresampled($new_image, $image, 0, 0, 0, 0, $dim['w'], $dim['h'], imagesx($image), imagesy($image));
			$image = $new_image;
			
			header("content-type:image/gif");
			imagegif($image);
		}
		elseif ($image_type == IMAGETYPE_PNG) 
		{
			$image = imagecreatefrompng($filename);
			
            $dim = $this->resize($width,$height,imagesx($image),imagesy($image));
			
			$new_image = imagecreatetruecolor($dim['w'], $dim['h']);
			imagecopyresampled($new_image, $image, 0, 0, 0, 0, $dim['w'], $dim['h'], imagesx($image), imagesy($image));
			$image = $new_image;
			
			header("content-type:image/png");
			imagepng($image);
		}

    }
    
    /**
	 * -------------------------------------------------------
	 * METHOD: croped_string
	 * -------------------------------------------------------
	 *
	 * This is crope the image propotionally within defined with and height.
	 * Function need to be called through following url
	 * http://elephanti.com/media/photos/croped_string/400/300/merchant/profile/albums/test/mac.gif
	 * refer base url through config key : [cdn_url]
	 * 
	 * So explanation will be like this 
	 * http://elephanti.com/media/photos/croped_string/width/height/dir1/dir2/image.gif
	 * 
	 * Here width and height is very important in same order but folder structure and file we can go in any level
	 * 
	 * @param (int)    width     |   with of the wraper content
	 * @param (int)    height    |   height of the wraper content
	 * @param (string) url    	 |   url of the image
	 *
	 */
    public function cropped_string()
    {
    	$args = func_get_args();		// assigning all parameters to variable as an array
    	
    	$width = $args[0];
		$height = $args[1];
		$filename = "";
    	
    	/**
    	 * validating for minimum 3 parameters
    	 */
    	if(count($args)<3 || !is_numeric($width) || !is_numeric($height))
    	{
    		show_404();
        	die;
    	}   	
		
		$path_array = array_slice($args,2);		// extract the url parameter in sub array		
		
		/**
		 * building url within cdn
		 */
		foreach($path_array as $path_val)
		{
			if($filename != "")
			{
				$filename .= "/";
			}
			
			$filename .= $path_val;
		}

		$filename = $this->media_url . $filename;
		
		$image_info = getimagesize($filename);
		
		$image_type = $image_info[2];
		
		if ($image_type == IMAGETYPE_JPEG) 
		{
			$image = imagecreatefromjpeg($filename);
			
            $dim = $this->resize($width,$height,imagesx($image),imagesy($image));
			
			$new_image = imagecreatetruecolor($dim['w'], $dim['h']);
			imagecopyresampled($new_image, $image, 0, 0, 0, 0, $dim['w'], $dim['h'], imagesx($image), imagesy($image));
			$image = $new_image;
						
			ob_start();
			imagejpeg($image);
			$outputBuffer = ob_get_clean();
			$base64 = 'data:image/jpeg;base64,' . base64_encode($outputBuffer);
			
		}
		elseif ($image_type == IMAGETYPE_GIF) 
		{
			$image = imagecreatefromgif($filename);
			
            $dim = $this->resize($width,$height,imagesx($image),imagesy($image));
			
			$new_image = imagecreatetruecolor($dim['w'], $dim['h']);
			imagecopyresampled($new_image, $image, 0, 0, 0, 0, $dim['w'], $dim['h'], imagesx($image), imagesy($image));
			$image = $new_image;
			
			ob_start();
			imagegif($image);
			$outputBuffer = ob_get_clean();
			$base64 = 'data:image/jpeg;base64,' . base64_encode($outputBuffer);
		}
		elseif ($image_type == IMAGETYPE_PNG) 
		{
			$image = imagecreatefrompng($filename);
			
            $dim = $this->resize($width,$height,imagesx($image),imagesy($image));
			
			$new_image = imagecreatetruecolor($dim['w'], $dim['h']);
			imagecopyresampled($new_image, $image, 0, 0, 0, 0, $dim['w'], $dim['h'], imagesx($image), imagesy($image));
			$image = $new_image;

			ob_start();
			imagepng($image);
			$outputBuffer = ob_get_clean();
			$base64 = 'data:image/jpeg;base64,' . base64_encode($outputBuffer);
		}
		$out_put['img'] = $base64;
		$out_put['w'] = imagesx($image);
		$out_put['h'] = imagesy($image);
		echo json_encode($out_put);

    }
    
    /**
	 * -------------------------------------------------------
	 * METHOD: cropped_string_simple
	 * -------------------------------------------------------
	 *
	 * This is crope the image propotionally within defined with and height.
	 * Function need to be called through following url
	 * http://elephanti.com/media/photos/cropped_string_simple/400/300/merchant/profile/albums/test/mac.gif
	 * refer base url through config key : [cdn_url]
	 * 
	 * So explanation will be like this 
	 * http://elephanti.com/media/photos/cropped_string_simple/width/height/dir1/dir2/image.gif
	 * 
	 * Here width and height is very important in same order but folder structure and file we can go in any level
	 * 
	 * @param (int)    width     |   with of the wraper content
	 * @param (int)    height    |   height of the wraper content
	 * @param (string) url    	 |   url of the image
	 *
	 */
    public function cropped_string_simple()
    {
    	$args = func_get_args();		// assigning all parameters to variable as an array
    	
    	$width = $args[0];
		$height = $args[1];
		$filename = "";
    	
    	/**
    	 * validating for minimum 3 parameters
    	 */
    	if(count($args)<3 || !is_numeric($width) || !is_numeric($height))
    	{
    		show_404();
        	die;
    	}   	
		
		$path_array = array_slice($args,2);		// extract the url parameter in sub array		
		
		/**
		 * building url within cdn
		 */
		foreach($path_array as $path_val)
		{
			if($filename != "")
			{
				$filename .= "/";
			}
			
			$filename .= $path_val;
		}

		$filename = $this->media_url . $filename;
		
		$image_info = getimagesize($filename);
		
		$image_type = $image_info[2];
		
		if ($image_type == IMAGETYPE_JPEG) 
		{
			$image = imagecreatefromjpeg($filename);
			
            $dim = $this->resize($width,$height,imagesx($image),imagesy($image));
			
			$new_image = imagecreatetruecolor($dim['w'], $dim['h']);
			imagecopyresampled($new_image, $image, 0, 0, 0, 0, $dim['w'], $dim['h'], imagesx($image), imagesy($image));
			$image = $new_image;
						
			ob_start();
			imagejpeg($image);
			$outputBuffer = ob_get_clean();
			$base64 = 'data:image/jpeg;base64,' . base64_encode($outputBuffer);
			
		}
		elseif ($image_type == IMAGETYPE_GIF) 
		{
			$image = imagecreatefromgif($filename);
			
            $dim = $this->resize($width,$height,imagesx($image),imagesy($image));
			
			$new_image = imagecreatetruecolor($dim['w'], $dim['h']);
			imagecopyresampled($new_image, $image, 0, 0, 0, 0, $dim['w'], $dim['h'], imagesx($image), imagesy($image));
			$image = $new_image;
			
			ob_start();
			imagegif($image);
			$outputBuffer = ob_get_clean();
			$base64 = 'data:image/jpeg;base64,' . base64_encode($outputBuffer);
		}
		elseif ($image_type == IMAGETYPE_PNG) 
		{
			$image = imagecreatefrompng($filename);
			
            $dim = $this->resize($width,$height,imagesx($image),imagesy($image));
			
			$new_image = imagecreatetruecolor($dim['w'], $dim['h']);
			imagecopyresampled($new_image, $image, 0, 0, 0, 0, $dim['w'], $dim['h'], imagesx($image), imagesy($image));
			$image = $new_image;

			ob_start();
			imagepng($image);
			$outputBuffer = ob_get_clean();
			$base64 = 'data:image/jpeg;base64,' . base64_encode($outputBuffer);
		}
		
		echo $base64;

    }
    
    private function fill($w,$h,$ow,$oh)
	{
		$r = $w/$h;
		$or = $ow/$oh;
		
		if(($ow < $w) && ($oh < $h))
		{
			$dim['w'] = $ow;
			$dim['h'] = $oh;
		}
		else if($or < $r)
		{
			$dim['w'] = $w;
			$dim['h'] = round($w/$ow * $oh);
		}
		else
		{
			$dim['w'] = round($h/$oh * $ow);
			$dim['h'] = $h;
		}
		
		/**
		 * latest requirement is to fill the box
		 * so this is the hack
		 */
		if(($ow < $w) || ($oh < $h))
		{
			$dim['w'] = $w;
			$dim['h'] = $h;
		}
		return $dim;
	}
	
	private function resize($w,$h,$ow,$oh)
	{
		$r = $w/$h;
		$or = $ow/$oh;
		
		if(($ow < $w) && ($oh < $h))
		{
			$dim['w'] = $ow;
			$dim['h'] = $oh;
		}
		else if($or > $r)
		{
			$dim['w'] = $w;
			$dim['h'] = round($w/$ow * $oh);
		}
		else
		{
			$dim['w'] = round($h/$oh * $ow);
			$dim['h'] = $h;
		}
		return $dim;
	}
	
	public function deploys3()
    {
    	$this->load->library('util/Cdn');
    	
    	$media_root = "F:/xampp/htdocs/";
    	$resource_array[] = "elephanti_media/merchant/profile/default/19850421/img1.jpg";
    	$resource_array[] = "elephanti_media/merchant/profile/albums/19850421/img1.jpg";
    	$resource_array[] = "elephanti_media/merchant/profile/albums/19850421/test/";
    	$this->cdn->deploy_s3($media_root,$resource_array);
    }
    
    /**
     * Dynamicaly create image for requested size(crop middle of the image)
     *
     * @access public
     * @param  void
     * @return array
     * @author Ruwan - ruwan.pathmalal@cyberlmj.com
     * 
     * usage: http://elephanti.com/media/photos/fine_cropped/width/height/dir1/dir2/image.gif
     **/
    public function fine_cropped(){
    	$args = func_get_args();
    	$final_img_width = $args[0];
    	$final_img_height = $args[1];
    	$filename = "";
    	 
    	/**
    	 * validating for minimum 3 parameters
    	 */
    	if(count($args)<3 || !is_numeric($final_img_width) || !is_numeric($final_img_height)){
			return false;
    	}
    	
    	// extract the url parameter in sub array
    	$path_array = array_slice($args,2);
    	
    	/**
    	 * building url within cdn
    	 */
    	foreach($path_array as $path_val){
    		if($filename != "")	{
    			$filename .= "/";
    		}
    		$filename .= $path_val;
    	}
    	
    	$source_image_path = $this->media_url . $filename;
    	list( $source_img_width, $source_img_height, $source_img_type ) = getimagesize( $source_image_path );
    	// if image width or height < requested width or height retern original image 
    	if($source_img_width > $final_img_width && $source_img_height > $final_img_height) {
	    	switch ( $source_img_type ) {
	    		case IMAGETYPE_GIF:	$source_img = imagecreatefromgif( $source_image_path );
	    							break;
	    		case IMAGETYPE_JPEG:$source_img = imagecreatefromjpeg( $source_image_path );
	    							break;
	    		case IMAGETYPE_PNG:	$source_img = imagecreatefrompng( $source_image_path );
	    							break;
	    			
	    	}
	    	
	    	$exif = @exif_read_data($source_image_path);
	    	$orientation = @$exif['Orientation'];
	    	
	    	if ($final_img_width == 0 && $final_img_height == 0){
	    	    if(isset($orientation) && ($orientation == 3 || $orientation == 6 || $orientation == 8) ){
					$source_img = $this->fix_orientation($orientation,$source_img);
				}
	    		header("content-type:image/jpeg");
	    		imagejpeg($source_img);
	    		exit;
	    	}
	    	
	    	$source_img_ratio = $source_img_width / $source_img_height;
	    	$final_img_ratio = $final_img_width / $final_img_height;
	    	
	    	if ( $source_img_ratio > $final_img_ratio )	{
	    		$temp_height = $final_img_height;
	    		$temp_width = ( int ) ( $final_img_height * $source_img_ratio );
	    	} else if($source_img_ratio == $final_img_ratio){
	    		$temp_height = $final_img_height;
	    		$temp_width = $final_img_height;
	    	} else {
	    		$temp_width = $final_img_width;
	    		$temp_height = ( int ) ( $final_img_width / $source_img_ratio );
	    	}
	    	
	    	$resize_img = imagecreatetruecolor( $temp_width, $temp_height );
	    	imagecopyresampled($resize_img,$source_img,0,0,0,0,$temp_width, $temp_height,$source_img_width, $source_img_height);
	    	$x0 = ( $temp_width - $final_img_width ) / 2;
	    	$y0 = ( $temp_height - $final_img_height ) / 2;
	    	
	    	$final_img = imagecreatetruecolor( $final_img_width, $final_img_height );
	    	imagecopy($final_img,$resize_img,0,0,$x0,$y0,$final_img_width,$final_img_height);
	    	imagedestroy( $source_img );
	    	imagedestroy( $resize_img );
	    	if(isset($orientation) && ($orientation == 3 || $orientation == 6 || $orientation == 8) ){
				$final_img = $this->fix_orientation($orientation,$final_img);
			}
	    	switch ( $source_img_type ) {
	    		case IMAGETYPE_GIF:	header("content-type:image/gif");
									imagegif($final_img);
	    							break;
	    		case IMAGETYPE_JPEG:header("content-type:image/jpeg");
									imagejpeg($final_img);
	    							break;
	    		case IMAGETYPE_PNG:	header("content-type:image/png");
									imagepng($final_img);	
									break;
	    	}
    	} else {
    		$source_img = file_get_contents($source_image_path);
    		    switch ( $source_img_type ) {
	    			case IMAGETYPE_GIF:	header("content-type:image/gif");
	    								echo $source_img;
	    								break;
	    			case IMAGETYPE_JPEG:header("content-type:image/jpeg");
	    								echo $source_img;
										break;
	    			case IMAGETYPE_PNG:	header("content-type:image/png");
										echo $source_img;
										break;
	    	}
    		exit;    		
    	}
    }
    
    public function fix_orientation($orientation,$image){
    	switch($orientation){
    		// 180 rotate left
    		case 3: $final_img = imagerotate($image, 180, 0);
    		break;
    		// 90 rotate right
    		case 6:	$final_img = imagerotate($image, -90, 0);
    		break;
    		// 90 rotate left
    		case 8:	$final_img = imagerotate($image, 90, 0);
    		break;
    
    	}
    	return $final_img;
    }
    
    public function img_resave()
    {
    	
    	$source = "temp/img1.png";
    	$destination = "temp/img5.png";
    	
    	$base_path = $this->config->item('server_root');
    	$source_image_path = $base_path . $source;
    	$destination_image_path = $base_path . $destination;
    	
    	list( $source_img_width, $source_img_height, $source_img_type ) = getimagesize( $source_image_path );   	   	
    	
    	switch ( $source_img_type ) {
    		case IMAGETYPE_GIF:	
				$image = imagecreatefromgif($source_image_path);
    			break;
    		case IMAGETYPE_JPEG:
    		
    			$image = imagecreatefromjpeg($source_image_path);  
    			  			
    			break;
    		case IMAGETYPE_PNG:	
    		
    			$image = imagecreatefrompng($source_image_path);
 				imagesavealpha($image, true);
				imagealphablending($image, false);

				break;
    	}
    	
    	$base = imagecreatetruecolor( 300, 300 ); 
    	imagecopyresampled($base, $image, 5, 5, 0, 0,300, 500, $source_img_width, $source_img_height);
		imagepng($base, $destination_image_path); 	
    	
    }    
    
	public function resize_save() {
		
		$this->load->library('util/image/Cropper');
		
		$source = "temp/img1.jpg";
		$destination = "temp/img5.jpg";
		
		$this->cropper->scale_down($source,$destination,$destination.".txt",600,418,1);
		
	}
    
    
}